package logic_basics

import (
	"APT/internal/dao"
	"APT/internal/library/contexts"
	"APT/internal/library/hgorm"
	"APT/internal/library/hgorm/handler"
	"APT/internal/library/hgorm/hook"
	"APT/internal/model/input/input_basics"
	"APT/internal/model/input/input_hotel"
	"APT/internal/service"
	"context"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"
	"strings"
)

type sBasicsCoupon struct{}

func NewBasicsCoupon() *sBasicsCoupon {
	return &sBasicsCoupon{}
}

func init() {
	service.RegisterBasicsCoupon(NewBasicsCoupon())
}

func (s *sBasicsCoupon) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.PmsCoupon.Ctx(ctx), option...)
}

func (s *sBasicsCoupon) View(ctx context.Context, in *input_basics.PmsCouponViewInp) (res *input_basics.PmsCouponViewModel, err error) {
	if err = s.Model(ctx).Hook(hook.PmsFindLanguageValueHook).WithAll().WherePri(in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取优惠券信息失败，请稍后重试！")
		return
	}

	if res.Scene == 1 {
		res.PropertyNames = "全部物业可用"
		if !g.IsEmpty(res.PropertyIds) {
			res.PropertyNames = ""
			var propertyArr []*input_hotel.PmsPropertyAllModel
			propertyArr, err = service.HotelService().PropertyAll(ctx, &input_hotel.PmsPropertyAllInp{
				Ids: res.PropertyIds,
			})
			if err != nil {
				err = gerror.Wrap(err, "获取物业失败！")
				return
			}
			if err = gvar.New(propertyArr).Struct(&res.Property); err != nil {
				return
			}
			// 获取物业名称以逗号 分隔
			for _, property := range propertyArr {
				res.PropertyNames = res.PropertyNames + property.Name + "，"
			}
			res.PropertyNames = gstr.TrimRight(res.PropertyNames, "，")
		}
	}

	if res.Scene == 2 {
		res.RestaurantNames = "全部门店可用"
		if !g.IsEmpty(res.RestaurantIds) {
			res.RestaurantNames = ""
			restaurantArr, _ := dao.FoodRestaurant.Ctx(ctx).WithAll().Hook(hook.PmsFindLanguageValueHook).Fields("name").
				WhereIn(dao.FoodRestaurant.Columns().Id, strings.Split(res.RestaurantIds, ",")).Array()

			if !g.IsEmpty(restaurantArr) {
				// 获取餐厅名称以逗号 分隔
				for _, restaurant := range restaurantArr {
					res.RestaurantNames = res.RestaurantNames + g.NewVar(restaurant).String() + "，"
				}
				res.RestaurantNames = gstr.TrimRight(res.RestaurantNames, "，")
			}
		}
	}

	if res.Scene == 3 {
		spaServiceTypeStr := "到店/上门"
		if !g.IsEmpty(res.ServiceIds) {
			spaServiceTypeStr = ""
			serviceIdsArr := strings.Split(res.ServiceIds, ",")
			for _, serviceType := range serviceIdsArr {
				switch serviceType {
				case "ToStore":
					spaServiceTypeStr = spaServiceTypeStr + "到店/"
					break
				case "ToDoor":
					spaServiceTypeStr = spaServiceTypeStr + "上门/"
					break
				}

			}
			spaServiceTypeStr = gstr.TrimRight(spaServiceTypeStr, "/")
		}
		res.SpaServiceTypeStr = spaServiceTypeStr
	}

	if res.Scene == 4 {
		carServiceTypeStr := "接机/送机/包车"
		if !g.IsEmpty(res.CarServiceTypes) {
			carServiceTypeStr = ""
			serviceTypeArr := strings.Split(res.CarServiceTypes, ",")
			for _, serviceType := range serviceTypeArr {
				switch serviceType {
				case "PICKUP":
					carServiceTypeStr = carServiceTypeStr + "接机/"
					break
				case "DELIVERY":
					carServiceTypeStr = carServiceTypeStr + "送机/"
					break
				case "CHARTERED":
					carServiceTypeStr = carServiceTypeStr + "包车/"
					break
				}
			}
			carServiceTypeStr = gstr.TrimRight(carServiceTypeStr, "/")
		}
		res.CarServiceTypeStr = carServiceTypeStr
	}

	return
}

func (s *sBasicsCoupon) List(ctx context.Context, in *input_basics.PmsCouponListInp) (list []*input_basics.PmsCouponListModel, totalCount int, err error) {
	mod := s.Model(ctx).WithAll().Hook(hook.PmsFindLanguageValueHook)

	mod = mod.FieldsPrefix(dao.PmsCoupon.Table(), input_basics.PmsCouponListModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, input_basics.PmsCouponListModel{}, &dao.PmsMember, "pmsMember"))

	mod = mod.LeftJoinOnFields(dao.PmsMember.Table(), dao.PmsCoupon.Columns().MemberId, "=", dao.PmsMember.Columns().Id)

	if in.CouponTypeId > 0 {
		mod = mod.Where(dao.PmsCoupon.Columns().CouponTypeId, in.CouponTypeId)
	}

	if in.State > 0 {
		mod = mod.Where(dao.PmsCoupon.Columns().State, in.State)
	}

	if !g.IsEmpty(in.MemberId) {
		mod = mod.Where(dao.PmsCoupon.Columns().MemberId, in.MemberId)
		mod = mod.OrderAsc(dao.PmsCoupon.Columns().State)
	}

	if !g.IsEmpty(in.WantUseTime) {
		//	mod = mod.Where("start_time IS NULL OR start_time <= ?", in.WantUseTime)
		//	mod = mod.Where("end_time IS NULL OR end_time >= ?", in.WantUseTime)
		mod = mod.WhereNull(dao.PmsCoupon.Columns().UseTime)
	}

	//if !g.IsEmpty(in.PropertyId) {
	//	mod = mod.Where("FIND_IN_SET(?, `property_ids`) > 0", in.PropertyId)
	//}

	if !g.IsEmpty(in.Scene) {
		mod = mod.Where(dao.PmsCoupon.Columns().Scene, in.Scene)
	}

	//if !g.IsEmpty(in.AtLeast) {
	//	mod = mod.WhereLTE(dao.PmsCoupon.Columns().AtLeast, in.AtLeast)
	//}

	if in.MemberKey != "" {
		mod = mod.Where(mod.Builder().
			WhereLike(dao.PmsMember.Columns().MemberNo, "%"+in.MemberKey+"%").
			WhereOrLike(dao.PmsMember.Columns().FullName, "%"+in.MemberKey+"%").
			WhereOrLike(dao.PmsMember.Columns().Phone, "%"+in.MemberKey+"%").
			WhereOrLike(dao.PmsMember.Columns().Mail, "%"+in.MemberKey+"%"))
	}

	if in.Source > 0 {
		mod = mod.Where(dao.PmsCoupon.Columns().Source, in.Source)
	}

	mod = mod.Page(in.Page, in.PerPage)

	mod = mod.OrderDesc(dao.PmsCoupon.Columns().Id)

	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		g.Log().Error(ctx, err)
		//err = gerror.Wrap(err, "获取列表失败，请稍后重试！")
		return
	}
	return
}

func (s *sBasicsCoupon) Stat(ctx context.Context, in *input_basics.PmsCouponStatInp) (res *input_basics.PmsCouponStatModel, err error) {
	res = &input_basics.PmsCouponStatModel{}
	mod := s.Model(ctx)

	totalSendNum, err := mod.Safe().Count()
	if err != nil {
		err = gerror.Wrap(err, "获取数据失败！")
		return
	}
	res.TotalSendNum = gvar.New(totalSendNum).Int()

	usedCount, err := mod.Safe().Where(dao.PmsCoupon.Columns().State, 2).Count()
	if err != nil {
		err = gerror.Wrap(err, "获取数据失败！")
		return
	}
	res.UsedNum = gvar.New(usedCount).Int()

	waitUseNum, err := mod.Safe().Where(dao.PmsCoupon.Columns().State, 1).Count()
	if err != nil {
		err = gerror.Wrap(err, "获取数据失败！")
		return
	}
	res.WaitUseNum = gvar.New(waitUseNum).Int()

	return
}

func (s *sBasicsCoupon) Recycle(ctx context.Context, in *input_basics.PmsCouponRecycleInp) (err error) {
	if _, err = s.Model(ctx).WherePri(in.Id).Data(g.Map{
		dao.PmsCoupon.Columns().State:        5,
		dao.PmsCoupon.Columns().OperatorId:   int(contexts.GetUserId(ctx)),
		dao.PmsCoupon.Columns().RecoveryTime: gtime.Now(),
	}).Update(); err != nil {
		err = gerror.Wrap(err, "优惠券回收失败，请稍后重试！")
		return
	}
	return
}
